package com.trayicon.messagenotifier.main;

import java.awt.AWTException;
import java.awt.Font;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import com.trayicon.messagenotifier.enums.ConfigEvent;


/**
 * 
 * @author locnv
 *
 */
public class ENSystemTray implements IConfigChangeListener {
	private TrayIcon trayIcon = null;
	private Timer timer = null;
	
	private ConfigFrame configFrame;
	private NotifyFrame notifierFrame;
	
	/**
	 * Default constructor
	 */
	public ENSystemTray() {
		init();
		
		timer = new Timer();
		DisplayNextWordTask task = new DisplayNextWordTask();
		timer.schedule(task, 5000, 60000);
		
		configFrame = new ConfigFrame();
		notifierFrame = new NotifyFrame();
		
		configFrame.addConfigChangeListener(this);
		configFrame.addConfigChangeListener(task);
		notifierFrame.registryConfigChangeListener(configFrame);
	}
	
	class DisplayNextWordTask extends TimerTask implements IConfigChangeListener {
		private boolean isShowRandom = true;
		private boolean isDisplayTurn = false; 
		
		@Override
		public void run() {
			if (trayIcon == null) {
				return;
			}
			
			isDisplayTurn = !isDisplayTurn;
			if (!isDisplayTurn) {
				if (notifierFrame!= null && notifierFrame.isVisible()) {
					notifierFrame.setVisible(false);
				}
			} else {
				Word w;
				if (isShowRandom) {
					w = CustomDictionary.GET().getRandomWord();	
				} else {
					w = CustomDictionary.GET().getNextWord();
				}
				
				if (w != null) {
					if (notifierFrame!= null && !notifierFrame.isVisible()) {
						notifierFrame.setVisible(true);
					}
					notifierFrame.setWord(w);
				}
			}
		}

		@Override
		public void configChange(ConfigEvent configEvent, Object value) {
			if (configEvent == ConfigEvent.SHOW_INORDER) {
				isShowRandom = false;
			} else if (configEvent == ConfigEvent.SHOW_RANDOM) {
				isShowRandom = true;
			}
		}
	}
	
	private void init() {
		if (!SystemTray.isSupported()) {
            return;
        }
		
		final SystemTray tray = SystemTray.getSystemTray();
		final PopupMenu popup = new PopupMenu();
		
		Image image = new ImageIcon(this.getClass().getResource("/icon_1.png")).getImage();
        trayIcon = new TrayIcon(image);
        // Create a pop-up menu components
        MenuItem aboutItem = new MenuItem("About");
        MenuItem manageItem = new MenuItem("Manage");
        MenuItem exitItem = new MenuItem("Exit");
        
        //Add components to pop-up menu
        popup.add(aboutItem);
        popup.add(manageItem);
        popup.addSeparator();
        popup.add(exitItem);
        trayIcon.setPopupMenu(popup);
        Font font = new Font("Verdana", Font.BOLD, 24);
        popup.setFont(font);
       
        try {
            tray.add(trayIcon);
            trayIcon.setImageAutoSize(true);
        } catch (AWTException e) {
            System.err.println("TrayIcon could not be added. Error: " + e.getMessage());
        }
        
        aboutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This simple app is written by locnv - locnv@gmail.com", "About", 1);
            }
        });
         
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MenuItem item = (MenuItem)e.getSource();
                if ("Manage".equals(item.getLabel())) {
                	configFrame.setVisible(true);
                     
                } else if ("None".equals(item.getLabel())) {
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an ordinary message", TrayIcon.MessageType.NONE);
                }
            }
        };
        manageItem.addActionListener(listener);
         
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	if (timer != null) {
            		timer.cancel();
            	}
                tray.remove(trayIcon);
                System.exit(0);
            }
        });
	}
	
	public void start() {
		//
	}

	public static void main(String args[]) {
		new ENSystemTray().start();
	}
	
	@Override
	public void configChange(ConfigEvent event, Object value) {
		if (event == ConfigEvent.ENABLE_NOTIFY_ON_TOP) {
			notifierFrame.setAlwaysOnTop1(true);
		} else if (event == ConfigEvent.DISABLE_NOTIFY_ON_TOP) {
			notifierFrame.setAlwaysOnTop1(false);
		}
	}
}
